<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-select class="filter-item" v-model="whereQuery.appId" clearable filterable remote placeholder="请输入应用名称" :remote-method="remoteMethod" @change="handleFilter" :loading="appLoading">
        <el-option v-for="item in appOptions" :key="item._id" :label="item.name" :value="item._id">
        </el-option>
      </el-select>
      <el-select clearable style="width: 120px" class="filter-item" v-model="whereQuery.status" placeholder="状态" @change="handleFilter">
        <el-option v-for="item in statusTypeOptions" :key="item" :label="item | statusTypeFilter" :value="item">
        </el-option>
      </el-select>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">添加</el-button>
    </div>

    <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row
              style="width: 100%" sortable="custom" @sort-change='handleOrder'>
      <el-table-column align="center" label="id" width="300">
        <template slot-scope="scope">
          <span class="link-type" style="font-family: Menlo, Monaco, Consolas, Courier New, monospace;" @click="showJsonObject(scope.row)">{{scope.row._id}}</span>
        </template>
      </el-table-column>
      <el-table-column width="135px" align="center" label="创建时间" sortable prop="createdAt">
        <template slot-scope="scope">
          <span>{{scope.row.createdAt | momentFormat('YYYY-MM-DD HH:mm')}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="180px" header-align="center" label="应用" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="link-type" v-if="scope.row.app" @click="showJsonObject(scope.row.app)">{{scope.row.app.name}}</span>
        </template>
      </el-table-column>
      <el-table-column width="100px" align="center" label="版本号">
        <template slot-scope="scope">
          <span>{{scope.row.versionName}}</span>
        </template>
      </el-table-column>
      <el-table-column width="90px" align="center" label="构建号">
        <template slot-scope="scope">
          <span>{{scope.row.versionCode}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="90px" label="缩略图">
        <template slot-scope="scope" v-if="scope.row.thumbnail && scope.row.thumbnail.url">
          <el-popover ref="thumbnailPopover" placement="top" width="220" trigger="hover">
            <el-form>
              <el-form-item min-width="200">
                <img :src="scope.row.thumbnail.url+'?imageView2/2/w/200/h/200'" class="avatar">
              </el-form-item>
            </el-form>
          </el-popover>
          <el-button v-popover:thumbnailPopover type="text"  @click="openWindow(scope.row.thumbnail.url)">thumbnail</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" width="90px" label="图标">
        <template slot-scope="scope" v-if="scope.row.icon && scope.row.icon.url">
          <el-popover ref="iconPopover" placement="top" width="220" trigger="hover">
            <el-form>
              <el-form-item min-width="200">
                <img :src="scope.row.icon.url+'?imageView2/2/w/200/h/200'" class="avatar">
              </el-form-item>
            </el-form>
          </el-popover>
          <el-button v-popover:iconPopover type="text"  @click="openWindow(scope.row.icon.url)">icon</el-button>
        </template>
      </el-table-column>
      <el-table-column header-align="center" width="210px" label="升级说明" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.notes}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="预览图" width="100">
        <template slot-scope="scope">
          <span class="link-type" v-if="scope.row.preview" @click="showPreview(scope.row)">编辑预览图</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="100px" label="预览视频">
        <template slot-scope="scope">
          <span class="link-type" v-if="scope.row.previewVideo && scope.row.previewVideo.url" @click="openWindow(scope.row.previewVideo.url)">video</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="100px" label="视频图">
        <template slot-scope="scope" v-if="scope.row.previewVideoPic && scope.row.previewVideoPic.url">
          <el-popover ref="previewVideoPicPopover" placement="top" width="220" trigger="hover">
            <el-form>
              <el-form-item min-width="200">
                <img :src="scope.row.previewVideoPic.url+'?imageView2/2/w/200/h/200'" class="avatar">
              </el-form-item>
            </el-form>
          </el-popover>
          <el-button v-popover:previewVideoPicPopover type="text"  @click="openWindow(scope.row.previewVideoPic.url)">videoPic</el-button>
        </template>
      </el-table-column>
      <el-table-column width="90px" align="center" label="评分" sortable prop="score">
        <template slot-scope="scope">
          <span>{{scope.row.score}}</span>
        </template>
      </el-table-column>
      <el-table-column width="120px" align="center" label="大小">
        <template slot-scope="scope">
          <span>{{scope.row.size}}</span>
        </template>
      </el-table-column>
      <el-table-column width="90px" align="center" label="下载量" sortable prop="downloads">
        <template slot-scope="scope">
          <span>{{scope.row.downloads}}</span>
        </template>
      </el-table-column>
      <el-table-column width="90px" align="center" label="浏览量" sortable prop="pageviews">
        <template slot-scope="scope">
          <span>{{scope.row.pageviews}}</span>
        </template>
      </el-table-column>
      <el-table-column width="120px" align="center" label="启动次数" sortable prop="opens">
        <template slot-scope="scope">
          <span>{{scope.row.opens}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" width="100px" label="应用文件">
        <template slot-scope="scope">
          <span class="link-type" v-if="scope.row.file && scope.row.file.url" @click="openWindow(scope.row.file.url)">下载</span>
        </template>
      </el-table-column>
      <el-table-column width="135px" align="center" label="上架时间">
        <template slot-scope="scope">
          <span v-if="scope.row.saleDate">{{scope.row.saleDate | momentFormat('YYYY-MM-DD')}}</span>
        </template>
      </el-table-column>
      <el-table-column width="90px" align="center" label="状态">
        <template slot-scope="scope">
          <span>{{scope.row.status | statusTypeFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="230" class-name="small-padding" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button size="mini" type="success" @click="changeStatus(scope.row)" v-bind:disabled="scope.row.status === 1">发布
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)" v-bind:disabled="scope.row.status === 1">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog title="对象" :visible.sync="jsonVisible">
      <el-form label-position="right" style='min-width: 600px;'>
        <el-form-item>
          <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 27}" v-model="jsonObject">
          </el-input>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="编辑预览图" :visible.sync="previewDialogVisible">
      <el-form label-position="right" style='min-width: 500px;'>
        <el-form-item>
          <div v-for="(element, index) in previewList"  class="upload-container">
            <div class="image-preview image-app-preview">
              <div style="justify-content: center; display: flex;">
                <img :src="element+'?imageView2/2/w/300/h/175'" class="avatar">
                <div class="image-preview-action">
                  <i @click="uploadPreviewPic(element, index)" class="el-icon-upload">更新 </i>
                  <i @click="openWindow(element)" class="el-icon-picture">查看 </i>
                  <i @click="deletePreview(element, index)" class="el-icon-remove">删除</i>
                </div>
              </div>
            </div>
          </div>
          <el-upload ref="upload" action="https://upload-z1.qbox.me" accept="image/*" :on-success = 'afterPreviewUpload' :data="previewObj" :multiple="false" :before-upload="beforePreviewUpload" :show-file-list="false">
            <el-button size="small" type="primary" v-bind:disabled="this.previewList.length > 4">添加预览图</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="previewDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="savePreview">保 存</el-button>
        </span>
    </el-dialog>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="90px" style='width: 650px; margin-left:20px;'>
        <el-form-item label="应用(id)">
          <el-col :span="12">
            <el-input style="width: 100%" v-model="temp.app._id" @blur="checkApp"></el-input>
          </el-col>
          <el-col class="line" :span="1">-</el-col>
          <el-col :span="11">
            <el-select style="width: 100%;" v-model="temp.app._id" clearable filterable remote placeholder="请输入关键词" :remote-method="remoteEditMethod" :loading="editAppLoading">
              <el-option v-for="item in appEditOptions" :key="item._id" :label="item.name" :value="item._id">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="版本号">
          <el-input v-model="temp.versionName"></el-input>
        </el-form-item>
        <el-form-item label="构建号" prop="versionCode" :rules="[{pattern: /^\d*$/,message: '构建号只能输入整数值'}]">
          <el-input v-model.number="temp.versionCode"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-upload class="avatar-uploader" action="https://upload-z1.qbox.me" accept="image/*" :data="iconObj" :multiple="false" :on-success='afterIconUpload' :before-upload="beforeIconUpload" :show-file-list="false">
            <img v-if="iconUrl" :src="temp.icon.url+'?imageView2/2/w/200/h/200'" class="avatar">
            <el-button v-else size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">请上传png、jpg及jpeg格式图片(大小2M以下,建议分辨率 xx * xx)</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="缩略图">
          <el-upload action="https://upload-z1.qbox.me" accept="image/*" :data="thumbnailObj" :multiple="false" :on-success='afterThumbnailUpload' :before-upload="beforeThumbnailUpload" :show-file-list="false">
            <img v-if="thumbnailUrl" :src="temp.thumbnail.url+'?imageView2/2/w/200/h/200'" class="avatar">
            <el-button v-else size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">请上传png、jpg及jpeg格式图片(大小2M以下,建议分辨率 xx * xx)</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="升级说明">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 6}" placeholder="请输入内容" v-model="temp.notes">
          </el-input>
        </el-form-item>
        <el-form-item label="视频预览图">
          <el-upload action="https://upload-z1.qbox.me" accept="image/*" :data="previewVideoPicObj" :multiple="false" :on-success='afterPreviewVideoPicUpload' :before-upload="beforePreviewVideoPicUpload" :show-file-list="false">
            <img v-if="previewVideoPicUrl" :src="temp.previewVideoPic.url+'?imageView2/2/w/200/h/200'" class="avatar">
            <el-button v-else size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">请上传png、jpg及jpeg格式图片(大小2M以下,建议分辨率 xx * xx)</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="预览视频">
          <el-upload class="upload-demo" accept=".mp4" action="https://upload-z1.qbox.me" :data="previewVideoObj" :multiple="false" :on-success='afterPreviewVideoUpload' :file-list="fileList" :before-upload="beforePreviewVideoUpload">
            <el-button v-if="previewVideoUrl" @click="openWindow(temp.previewVideo.url)" type="text">查看预览视频</el-button>
            <el-button size="small" type="primary">点击上传</el-button>
            <!--<div slot="tip" class="el-upload__tip">请上传MP4格式视频</div>-->
          </el-upload>
        </el-form-item>
        <el-form-item label="应用apk">
          <el-button v-if="fileUrl" @click="openWindow(temp.file.url)" type="text">下载apk</el-button>
          <el-button size="small" type="primary" id="uploadFile">点击上传</el-button>
          <upload browse_button='uploadFile' :uptoken="fileToken" :upkey="fileKey" accept="apk" v-on:on-success="afterFileUpload"></upload>
        </el-form-item>
        <el-form-item label="评分" prop="score" :rules="[{pattern: /^(\d+(\.\d{1,2})?)?$/,message: '评分只能输入数值'}]">
          <el-input v-model.number="temp.score"></el-input>
        </el-form-item>
        <el-form-item label="大小">
          <el-input v-model.number="temp.size" disabled></el-input>
        </el-form-item>
        <el-form-item label="下载量" prop="downloads" :rules="[{pattern: /^\d*$/,message: '下载量只能输入整数值'}]">
          <el-input v-model.number="temp.downloads"></el-input>
        </el-form-item>
        <el-form-item label="浏览量" prop="pageviews" :rules="[{pattern: /^\d*$/,message: '浏览量只能输入整数值'}]">
          <el-input v-model.number="temp.pageviews"></el-input>
        </el-form-item>
        <el-form-item label="启动次数" prop="opens" :rules="[{pattern: /^\d*$/,message: '启动次数只能输入整数值'}]">
          <el-input v-model.number="temp.opens"></el-input>
        </el-form-item>
        <el-form-item label="上架时间">
          <el-date-picker v-model="temp.saleDate" type="date" placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确 定</el-button>
        <el-button v-else type="primary" @click="updateData">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { fetch, getObjectById, insert, deleteById, update, cloud } from '@/api/jb'
  import { getToken } from '@/api/qiniu'
  import waves from '@/directive/waves' // 水波纹指令
  import { MessageBox, Message } from 'element-ui'
  import Upload from '@/components/Upload'
  require('qiniu-js/dist/qiniu.min.js')

  const booleanOptions = [
    { key: true, value: '是' },
    { key: false, value: '否' }
  ]

  export default {
    name: 'versionInfo',
    components: { Upload },
    directives: {
      waves
    },
    data() {
      return {
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          skip: 0,
          limit: 10,
          include: 'app',
          where: {
            app: {
              __type: 'Pointer',
              className: 'App',
              _id: undefined
            },
            status: undefined
          },
          count: true,
          order: {
            updatedAt: -1
          }
        },
        fileList: [],
        appOptions: [],
        appEditOptions: [],
        whereQuery: {
          appId: undefined,
          status: undefined
        },
        appLoading: false,
        editAppLoading: false,
        listAppQuery: {
          skip: 0,
          limit: 10,
          keys: ['_id', 'name'],
          where: {
            name: {
              $regex: '.*'
            }
          },
          order: {
            weight: -1
          }
        },
        statusTypeOptions: [1, 2, 3],
        booleanOptions,
        temp: {
          _id: undefined,
          app: {
            _id: undefined,
            __type: 'Pointer',
            className: 'App'
          },
          versionName: undefined,
          versionCode: undefined,
          thumbnail: {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          },
          icon: {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          },
          notes: undefined,
          preview: [],
          previewVideo: {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          },
          previewVideoPic: {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          },
          score: undefined,
          size: undefined,
          downloads: undefined,
          pageviews: undefined,
          opens: undefined,
          file: {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          },
          saleDate: undefined,
          status: 0
        },
        previewDialogVisible: false,
        previewList: [],
        previewEditEle: undefined,
        previewSuperId: undefined,
        iconObj: { token: '', key: '' },
        thumbnailObj: { token: '', key: '' },
        previewVideoObj: { token: '', key: '' },
        previewObj: { token: '', key: '' },
        previewVideoPicObj: { token: '', key: '' },
        fileObj: { token: 'aaaa', key: '' },
        iconUrl: undefined,
        thumbnailUrl: undefined,
        previewVideoUrl: undefined,
        previewVideoPicUrl: undefined,
        fileUrl: undefined,
        fileToken: undefined,
        fileKey: undefined,
        fileData: {
          _id: undefined,
          url: undefined,
          size: undefined
        },
        qiniuParams: {
          fileName: 'versionInfo',
          platform: 'qiniu'
        },
        dialogFormVisible: false,
        jsonVisible: false,
        jsonObject: undefined,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        rules: {
          status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
        }
      }
    },
    filters: {
      statusTypeFilter(status) {
        const statusType = ['销售中', '老版本', '待发布']
        return status > 0 ? statusType[status - 1] : ''
      },
      json: (value) => { return JSON.stringify(value, null, 2) }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        if (this.whereQuery.appId) {
          this.listQuery.where.app = {
            __type: 'Pointer',
            className: 'App',
            _id: this.whereQuery.appId
          }
        } else {
          this.listQuery.where.app = undefined
        }
        fetch('VersionInfo', this.listQuery).then(response => {
          this.list = response.data.data.result
          this.total = response.data.data.count
          this.listLoading = false
        })
      },
      remoteMethod(keyword) {
        if (this.appLoading) {
          return
        }
        if (keyword !== '') {
          this.appLoading = true
          setTimeout(() => {
            this.appLoading = false
            this.listAppQuery.where.name = {
              $regex: '.*' + keyword + '.*'
            }
            fetch('App', this.listAppQuery).then(response => {
              this.appOptions = response.data.data.result
            })
          }, 200)
        } else {
          this.appOptions = []
        }
      },
      remoteEditMethod(keyword) {
        if (this.editAppLoading) {
          return
        }
        if (keyword !== '') {
          this.editAppLoading = true
          setTimeout(() => {
            this.editAppLoading = false
            this.listAppQuery.where.name = {
              $regex: '.*' + keyword + '.*'
            }
            fetch('App', this.listAppQuery).then(response => {
              this.appEditOptions = response.data.data.result
            })
          }, 200)
        } else {
          this.appEditOptions = []
        }
      },
      checkApp() {
        if (this.temp.app._id) {
          var flag = false
          for (const item in this.appEditOptions) {
            if (this.appEditOptions[item]._id === this.temp.app._id) {
              flag = true
              break
            }
          }
          if (flag) {
            return
          }
          getObjectById('App', this.temp.app._id).then(response => {
            this.appEditOptions.push(response.data.data.result)
          })
        }
      },

      savePreview() {
        const body = {
          preview: this.previewList.size === 0 ? {
            __op: 'Delete'
          } : this.previewList
        }
        update('VersionInfo', this.previewSuperId, body).then(() => {
          this.previewDialogVisible = false
          this.$notify({
            title: '成功',
            message: '修改预览图成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      },
      showPreview(row) {
        this.previewDialogVisible = true
        this.previewList = row.preview ? row.preview.slice(0) : []
        this.previewSuperId = row._id
      },
      deletePreview(element, index) {
        this.previewList.splice(index, 1)
      },
      uploadPreviewPic() {
        alert('更新图片')
        // this.$refs.upload.upload();
      },
      handleOrder(sort) {
        if (sort.prop) {
          const order = {}
          order[sort.prop] = sort.order === 'ascending' ? 1 : -1
          this.listQuery.order = order
        } else {
          this.listQuery.order = {
            updatedAt: -1
          }
        }
        this.getList()
      },
      handleFilter() {
        this.listQuery.skip = 0
        if (this.whereQuery.appId) {
          this.listQuery.where.app = {
            __type: 'Pointer',
            className: 'App',
            _id: this.whereQuery.appId
          }
        } else {
          this.listQuery.where.app = undefined
        }
        if (this.whereQuery.status) {
          this.listQuery.where.status = this.whereQuery.status
        } else {
          this.listQuery.where.status = undefined
        }
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.limit = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.skip = (val - 1) * this.listQuery.limit
        this.getList()
      },
      resetTemp() {
        this.temp = {
          _id: undefined,
          app: {
            _id: undefined,
            __type: 'Pointer',
            className: 'App'
          },
          versionName: undefined,
          versionCode: undefined,
          thumbnail: {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          },
          icon: {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          },
          notes: undefined,
          preview: [],
          previewVideo: {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          },
          previewVideoPic: {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          },
          score: undefined,
          size: undefined,
          downloads: undefined,
          pageviews: undefined,
          opens: undefined,
          file: {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          },
          saleDate: undefined,
          status: 0
        }
      },
      beforeUpload(file, type) {
        const _self = this
        return new Promise((resolve, reject) => {
          getToken(this.qiniuParams).then(response => {
            const key = response.data.data.name
            const token = response.data.data.token
            if (type === 1) {
              // icon
              _self._data.iconObj.token = token
              _self._data.iconObj.key = key
            } else if (type === 2) {
              // thumbnail
              _self._data.thumbnailObj.token = token
              _self._data.thumbnailObj.key = key
            } else if (type === 3) {
              // previewVideo
              _self._data.previewVideoObj.token = token
              _self._data.previewVideoObj.key = key
            } else if (type === 4) {
              // previewVideoPic
              _self._data.previewVideoPicObj.token = token
              _self._data.previewVideoPicObj.key = key
            } else if (type === 5) {
              // file
              _self._data.fileObj.token = token
              _self._data.fileObj.key = key
            } else if (type === 6) {
              _self._data.previewObj.token = token
              _self._data.previewObj.key = key
            }
            resolve(true)
          }).catch(err => {
            console.log(err)
            reject(false)
          })
        })
      },
      beforeIconUpload(file) {
        return this.beforeUpload(file, 1)
      },
      beforeThumbnailUpload(file) {
        return this.beforeUpload(file, 2)
      },
      beforePreviewVideoUpload(file) {
        return this.beforeUpload(file, 3)
      },
      beforePreviewVideoPicUpload(file) {
        return this.beforeUpload(file, 4)
      },
      beforeFileUpload(file) {
        return this.beforeUpload(file, 5)
      },
      beforePreviewUpload(file) {
        return this.beforeUpload(file, 6)
      },
      afterIconUpload(res) {
        this.temp.icon._id = res.data.file._id
        this.temp.icon.url = res.data.file.url
        this.iconUrl = res.data.file.url
      },
      afterThumbnailUpload(res) {
        this.temp.thumbnail._id = res.data.file._id
        this.temp.thumbnail.url = res.data.file.url
        this.thumbnailUrl = res.data.file.url
      },
      afterPreviewVideoUpload(res) {
        this.temp.previewVideo._id = res.data.file._id
        this.temp.previewVideo.url = res.data.file.url
        this.previewVideoUrl = res.data.file.url
        this.fileList = []
      },
      afterPreviewVideoPicUpload(res) {
        this.temp.previewVideoPic._id = res.data.file._id
        this.temp.previewVideoPic.url = res.data.file.url
        this.previewVideoPicUrl = res.data.file.url
      },
      afterFileUpload(res) {
        this.temp.file._id = res._id
        this.temp.file.url = res.url
        this.fileUrl = res.url
        this.temp.size = res.size
      },
      afterPreviewUpload(res) {
        this.previewList.push(res.data.file.url)
      },
      handleCreate() {
        this.resetTemp()
        getToken(this.qiniuParams).then(response => {
          const key = response.data.data.name
          const token = response.data.data.token
          this.fileToken = token
          this.fileKey = key
          this.iconUrl = undefined
          this.thumbnailUrl = undefined
          this.previewVideoUrl = undefined
          this.previewVideoPicUrl = undefined
          this.fileUrl = undefined
          this.dialogStatus = 'create'
          this.dialogFormVisible = true
          this.appEditOptions = []
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            if (!this.temp.app._id) {
              tempData.app = undefined
            }
            if (!this.temp.thumbnail._id) {
              tempData.thumbnail = undefined
            }
            if (!this.temp.icon._id) {
              tempData.icon = undefined
            }
            if (!this.temp.previewVideo._id) {
              tempData.previewVideo = undefined
            }
            if (!this.temp.previewVideoPic._id) {
              tempData.previewVideoPic = undefined
            }
            if (!this.temp.file._id) {
              tempData.file = undefined
            }
            if (this.temp.saleDate) {
              tempData.saleDate = new Date(this.temp.saleDate).getTime()
            }
            insert('VersionInfo', tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
              this.listQuery.skip = 0
              this.getList()
            })
          }
        })
      },
      handleUpdate(row) {
        for (const key of Reflect.ownKeys(this.temp)) {
          this.temp[key] = row[key]
        }
        if (this.temp.app) {
          this.appEditOptions = [{
            '_id': row.app._id,
            'name': row.app.name
          }]
        } else {
          this.temp.app = {
            _id: undefined,
            __type: 'Pointer',
            className: 'App'
          }
        }
        if (!this.temp.thumbnail) {
          this.temp.thumbnail = {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          }
          this.thumbnailUrl = undefined
        } else {
          this.thumbnailUrl = this.temp.thumbnail.url
        }
        if (!this.temp.icon) {
          this.temp.icon = {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          }
          this.iconUrl = undefined
        } else {
          this.iconUrl = this.temp.icon.url
        }
        if (!this.temp.previewVideo) {
          this.temp.previewVideo = {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          }
          this.previewVideoUrl = undefined
        } else {
          this.previewVideoUrl = this.temp.previewVideo.url
        }
        if (!this.temp.previewVideoPic) {
          this.temp.previewVideoPic = {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          }
          this.previewVideoPicUrl = undefined
        } else {
          this.previewVideoPicUrl = this.temp.previewVideoPic.url
        }
        if (!this.temp.file) {
          this.temp.file = {
            _id: undefined,
            __type: 'File',
            className: '_File',
            url: undefined
          }
          this.fileUrl = undefined
        } else {
          this.fileUrl = this.temp.file.url
        }
        getToken(this.qiniuParams).then(response => {
          const key = response.data.data.name
          const token = response.data.data.token
          this.fileToken = token
          this.fileKey = key
          this.dialogStatus = 'update'
          this.dialogFormVisible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            if (!this.temp.icon._id) {
              tempData.icon = undefined
            }
            if (!this.temp.thumbnail._id) {
              tempData.thumbnail = undefined
            }
            if (!this.temp.previewVideo._id) {
              tempData.previewVideo = undefined
            }
            if (!this.temp.previewVideoPic._id) {
              tempData.previewVideoPic = undefined
            }
            if (!this.temp.file._id) {
              tempData.file = undefined
            }
            if (this.temp.saleDate) {
              tempData.saleDate = new Date(this.temp.saleDate).getTime()
            }
            if (!this.temp.app._id) {
              tempData.app = undefined
            }
            update('VersionInfo', this.temp._id, tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
          }
        })
      },
      changeStatus(row) {
        if (!row.app) {
          Message({
            message: '应用数据缺失，请检查',
            type: 'error',
            duration: 5 * 1000
          })
          return
        }
        MessageBox.confirm('是否发布"' + row.versionName + '"版本，点击发布后线上版本将被替换？', row.app.name, {
          confirmButtonText: '发布',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const params = {
            'versionInfoId': row._id
          }
          cloud('changeVersionInfoStatus', params).then(response => {
            if (response.data.code === 0) {
              this.$notify({
                title: '成功',
                message: '发布成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            } else {
              this.$notify({
                title: '失败',
                message: response.data.message,
                type: 'info',
                duration: 2000
              })
            }
          })
        })
      },
      handleDelete(row) {
        MessageBox.confirm('是否确认删除？', '确定删除', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteById('VersionInfo', row._id).then(response => {
            if (response.data.code === 0) {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              const index = this.list.indexOf(row)
              this.list.splice(index, 1)
            } else {
              this.$notify({
                title: '失败',
                message: response.data.message,
                type: 'info',
                duration: 2000
              })
            }
          })
        })
      },
      showJsonObject(data) {
        this.jsonVisible = true
        this.jsonObject = JSON.stringify(data, null, 4)
      },
      openWindow(value) {
        window.open(value)
      }
    }
  }
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  @import "src/styles/mixin.scss";
  .upload-container {
    width: 100%;
    position: relative;
  @include clearfix;
  .image-uploader {
    width: 35%;
    float: left;
  }
  .image-preview {
    width: 200px;
    height: 200px;
    position: relative;
    border: 1px dashed #d9d9d9;
    float: left;
    margin-left: 50px;
  .image-preview-wrapper {
    position: relative;
    width: 100%;
    height: 100%;
  img {
    width: 100%;
    height: 100%;
  }
  }
  .image-preview-action {
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    cursor: default;
    text-align: center;
    color: #fff;
    opacity: 0;
    font-size: 20px;
    background-color: rgba(0, 0, 0, .5);
    transition: opacity .3s;
    cursor: pointer;
    text-align: center;
    line-height: 200px;
  .el-icon-delete {
    font-size: 36px;
  }
  }
  &:hover {
  .image-preview-action {
    opacity: 1;
  }
  }
  }
  .image-app-preview {
    width: 320px;
    height: 180px;
    position: relative;
    border: 1px dashed #d9d9d9;
    float: left;
    margin-left: 50px;
  .app-fake-conver {
    height: 44px;
    position: absolute;
    width: 100%; // background: rgba(0, 0, 0, .1);
    text-align: center;
    line-height: 64px;
    color: #fff;
  }
  }
  }
</style>
